package server;

import config.Context;
import config.Host;
import config.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class ServletProcessor4 extends Thread {

    private Socket socket;
    private List<Host> hosts;

    public ServletProcessor4(Socket socket, List<Host> hosts) {
        this.socket = socket;
        this.hosts = hosts;
    }

    @Override
    public void run() {
        try {
            // 有了 socket，接收到请求，获取输入流
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            Host newHost = null;
            // 获取host信息
            for (Host host : hosts) {
                if (host.getName().equals(request.getHost())) {
                    newHost = host;
                    break;
                }
            }
            if (newHost == null) {
                throw new Exception("host 不存在");
            }

            Context newContext = null;
            // 获取context
            List<Context> contexts = newHost.getContexts();
            for (Context context : contexts) {
                if (context.getName().equals(request.getProjectName())) {
                    newContext = context;
                    break;
                }
            }
            if (newContext == null) {
                throw new Exception("该项目不存在");
            }

            Servlet servlet = null;
            // 获取servlet
            List<Wrapper> wrappers = newContext.getWrappers();
            for (Wrapper wrapper : wrappers) {
                if (wrapper.getName().equals(request.getUrl())) {
                    servlet = wrapper.getServlet();
                    break;
                }
            }

            // 静态资源处理
            if (servlet == null) {
                response.outputHtml(request.getUrl());
            }else {// 动态资源servlet处理
                HttpServlet httpServlet = (HttpServlet) servlet;
                httpServlet.service(request, response);
            }

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
